angular.module('baisonService', []).factory('apiService', ['$rootScope', '$http', '$location',
    function ($rootScope, $http, $location) {
        var datetime = new Date();
        var year = datetime.getFullYear();
        var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
        var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
        var date_str = year + "-" + month + "-" + date;
        var get_sign = function () {
            var configData = $api.getStorage('configData');
            var efast365_key = configData.shanghu;
            var efast365_pass = '123456';//configData.shanghu_password;
            var str = efast365_key + efast365_pass + date_str;
            var sign = $.md5(str);
            return sign;
        };
        return function (url, param) {
            var configData = $api.getStorage('configData');
            var base_url = '';
            base_url = configData.api_url;

            var post_url = base_url + url;
            param.key = configData.shanghu;
            param.sign = get_sign();
            var datetime = new Date();
            param.time = parseInt(datetime.getTime() / 1000);
            //baison_app.api.alert({msg:post_url,title:'post_url'});
            //请求返回
            var is_response = false;
            var result_res = {};
            result_res =  $http.post(post_url, param).success(function (ret) {
                is_response = true;
                if (ret.message == 'timeerror') {
                    var post_url = base_url + 'sys/message/get_time';
                    $http.post(post_url, param).success(function (ret) {
//          		    baison_app.api.alert({title:'111',msg:ret});
                        var sever_time = ret.data;
                        var sys_type = baison_app.api.systemType;
                        var path = '';
                        if (sys_type == 'ios') {
                            path = $rootScope.language.TIP_SETTING_GENERAL_DATETIME;
                        } else if (sys_type == 'android') {
                            path = $rootScope.language.TIP_SETTING_DATETIME;
                        } else {
                            path = $rootScope.language.TIP_SETTING_CONTROLPANEL_DATETIME;
                        }
                        baison_app.api.toast({duration: 4000, msg: $rootScope.language.TIP_CHECK_SYSTEM_TIME + '\r\n' + $rootScope.language.TIP_SERVER_TIME  + sever_time + '\r\n' + $rootScope.language.TIP_MODIFY_TIME_PATH + path});
                    });
                    $location.path('/index');
                }
            });
            //console.log($rootScope.wait_twifi);
            var wait_time_out = {};
            wait_time_out = setTimeout(function () {
                clearInterval(wait_time_out);
                if(!is_response){
                    baison_app.api.hideProgress();
                    baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: "网络信号差,请稍等..."}); 
                }
                
            }, $rootScope.wait_twifi);

            return result_res;
            //return $http.post(post_url, param);
        };
    }])
        .factory('socket', ['$rootScope',function ($rootScope) {
            var socket = io.connect('http://121.41.36.202:443/');
            return {
                on: function (eventName, callback) {
                    socket.on(eventName, function () {
                        var args = arguments;
                        $rootScope.$apply(function () {
                            callback.apply(socket, args);
                        });
                    });
                },
                emit: function (eventName, data, callback) {
                    socket.emit(eventName, data, function () {
                        var args = arguments;
                        $rootScope.$apply(function () {
                            if (callback) {
                                callback.apply(socket, args);
                            }
                        });
                    });
                }
            };
        }])
        /**
         * 格式化时间方法
         * @param {number|date} time 时间戳，0代表当前时间, 其他时间请传入date类型对象
         * @param {string} type 输出类型,支持日期和时间：datetime格式化为2015-05-01 12:12:12; date格式化为2015-05-01
         * @returns {string} 返回时间字符串
         */
        .factory('timeStamp2String', [function () {
                return function (time, type) {
                    var datetime = new Date();
                    if (0 !== time) {
                        //datetime.setTime(time);
                        datetime = time;
                    }
                    if (typeof time === 'string') {
                        //替换日期中的-为/
                        time = time.replace(/-/g, '/');
                        datetime = new Date(time);
                    }
                    if (typeof time === 'number' && 0 !== time) {
                        datetime = new Date(time);

                    }

                    var year = datetime.getFullYear();
                    var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
                    var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
                    var hour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
                    var minute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
                    var second = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
                    var day = datetime.getDay();
                    //返回周几 周日为0
                    if (type === 'datetime') {
                        return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
                    }
                    //年月日时分秒 年以2位 
                    if (type === 'datetime2') {
                        return year.toString().substr(2, 2) + "" + month + "" + date + "" + hour + "" + minute + "" + second;
                    }
                    if (type === 'date') {
                        return year + "-" + month + "-" + date;
                    }
                    if (type === 'time') {
                        return (hour + ":" + minute + ' ') + ((hour <= 12) ? 'AM' : 'PM');
                    }
                    if (type === 'time_2') {
                        return (hour + ":" + minute + ' ');
                    }
                    if (type === 'day') {
                        return day == 0 ? 7 : day;
                    }
                    if (type === 'month') {
                        return month;
                    }
                    if (type === 'month-day') {
                        return month + "-" + date;
                    }
                    if (type === 'birthday') {
                        return year + month + date;
                    }

                };
            }])
        /**
         * 将json对象转换成为xml字符串
         * @date 2015-07-14
         * @author jhua.zuo <jhua.zuo@baisonmail.com>
         * @param {object} param 待转换对象
         * @returns {string}
         */
        .factory('jsonToXml', [function () {
                return function (param) {
                    var xml = '<xml>';
                    $.each(param, function (key, val) {
                        if (isNaN(new Number(val))) {
                            xml = xml + '<' + key + '><![CDATA[' + val + ']]></' + key + '>';
                        } else {
                            xml = xml + '<' + key + '>' + val + '</' + key + '>';
                        }
                    });
                    xml = xml + '</xml>';
                    return xml;
                };
            }])
        /**
         *
         * @param {string} element or document DOM node
         * @param {string} tab or indent string for pretty output formatting omit or use empty string "" to supress.
         * @link http://goessner.net/download/prj/jsonxml/
         */
        .factory('xmlToJson', [function () {
                return function (xml, tab) {
                    var X = {
                        toObj: function (xml) {
                            var o = {};
                            if (xml.nodeType == 1) {   // element node ..
                                if (xml.attributes.length)   // element with attributes  ..
                                    for (var i = 0; i < xml.attributes.length; i++)
                                        o["@" + xml.attributes[i].nodeName] = (xml.attributes[i].nodeValue || "").toString();
                                if (xml.firstChild) { // element has child nodes ..
                                    var textChild = 0, cdataChild = 0, hasElementChild = false;
                                    for (var n = xml.firstChild; n; n = n.nextSibling) {
                                        if (n.nodeType == 1)
                                            hasElementChild = true;
                                        else if (n.nodeType == 3 && n.nodeValue.match(/[^ \f\n\r\t\v]/))
                                            textChild++; // non-whitespace text
                                        else if (n.nodeType == 4)
                                            cdataChild++; // cdata section node
                                    }
                                    if (hasElementChild) {
                                        if (textChild < 2 && cdataChild < 2) { // structured element with evtl. a single text or/and cdata node ..
                                            X.removeWhite(xml);
                                            for (var n = xml.firstChild; n; n = n.nextSibling) {
                                                if (n.nodeType == 3)  // text node
                                                    o["#text"] = X.escape(n.nodeValue);
                                                else if (n.nodeType == 4)  // cdata node
                                                    o["#cdata"] = X.escape(n.nodeValue);
                                                else if (o[n.nodeName]) {  // multiple occurence of element ..
                                                    if (o[n.nodeName] instanceof Array)
                                                        o[n.nodeName][o[n.nodeName].length] = X.toObj(n);
                                                    else
                                                        o[n.nodeName] = [o[n.nodeName], X.toObj(n)];
                                                } else  // first occurence of element..
                                                    o[n.nodeName] = X.toObj(n);
                                            }
                                        } else { // mixed content
                                            if (!xml.attributes.length)
                                                o = X.escape(X.innerXml(xml));
                                            else
                                                o["#text"] = X.escape(X.innerXml(xml));
                                        }
                                    } else if (textChild) { // pure text
                                        if (!xml.attributes.length)
                                            o = X.escape(X.innerXml(xml));
                                        else
                                            o["#text"] = X.escape(X.innerXml(xml));
                                    } else if (cdataChild) { // cdata
                                        if (cdataChild > 1)
                                            o = X.escape(X.innerXml(xml));
                                        else
                                            for (var n = xml.firstChild; n; n = n.nextSibling)
                                                o["#cdata"] = X.escape(n.nodeValue);
                                    }
                                }
                                if (!xml.attributes.length && !xml.firstChild)
                                    o = null;
                            } else if (xml.nodeType == 9) { // document.node
                                o = X.toObj(xml.documentElement);
                            } else
                                alert("unhandled node type: " + xml.nodeType);
                            return o;
                        },
                        toJson: function (o, name, ind) {
                            var json = name ? ("\"" + name + "\"") : "";
                            if (o instanceof Array) {
                                for (var i = 0, n = o.length; i < n; i++)
                                    o[i] = X.toJson(o[i], "", ind + "\t");
                                json += (name ? ":[" : "[") + (o.length > 1 ? ("\n" + ind + "\t" + o.join(",\n" + ind + "\t") + "\n" + ind) : o.join("")) + "]";
                            } else if (o == null)
                                json += (name && ":") + "null";
                            else if (typeof (o) == "object") {
                                var arr = [];
                                for (var m in o)
                                    arr[arr.length] = X.toJson(o[m], m, ind + "\t");
                                json += (name ? ":{" : "{") + (arr.length > 1 ? ("\n" + ind + "\t" + arr.join(",\n" + ind + "\t") + "\n" + ind) : arr.join("")) + "}";
                            } else if (typeof (o) == "string")
                                json += (name && ":") + "\"" + o.toString() + "\"";
                            else
                                json += (name && ":") + o.toString();
                            return json;
                        },
                        innerXml: function (node) {
                            var s = ""
                            if ("innerHTML" in node)
                                s = node.innerHTML;
                            else {
                                var asXml = function (n) {
                                    var s = "";
                                    if (n.nodeType == 1) {
                                        s += "<" + n.nodeName;
                                        for (var i = 0; i < n.attributes.length; i++)
                                            s += " " + n.attributes[i].nodeName + "=\"" + (n.attributes[i].nodeValue || "").toString() + "\"";
                                        if (n.firstChild) {
                                            s += ">";
                                            for (var c = n.firstChild; c; c = c.nextSibling)
                                                s += asXml(c);
                                            s += "</" + n.nodeName + ">";
                                        } else
                                            s += "/>";
                                    } else if (n.nodeType == 3)
                                        s += n.nodeValue;
                                    else if (n.nodeType == 4)
                                        s += "<![CDATA[" + n.nodeValue + "]]>";
                                    return s;
                                };
                                for (var c = node.firstChild; c; c = c.nextSibling)
                                    s += asXml(c);
                            }
                            return s;
                        },
                        escape: function (txt) {
                            return txt.replace(/[\\]/g, "\\\\")
                                    .replace(/[\"]/g, '\\"')
                                    .replace(/[\n]/g, '\\n')
                                    .replace(/[\r]/g, '\\r');
                        },
                        removeWhite: function (e) {
                            e.normalize();
                            for (var n = e.firstChild; n; ) {
                                if (n.nodeType == 3) {  // text node
                                    if (!n.nodeValue.match(/[^ \f\n\r\t\v]/)) { // pure whitespace text node
                                        var nxt = n.nextSibling;
                                        e.removeChild(n);
                                        n = nxt;
                                    } else
                                        n = n.nextSibling;
                                } else if (n.nodeType == 1) {  // element node
                                    X.removeWhite(n);
                                    n = n.nextSibling;
                                } else                      // any other node
                                    n = n.nextSibling;
                            }
                            return e;
                        }
                    };
                    if (xml.nodeType == 9) // document node
                        xml = xml.documentElement;
                    var json = X.toJson(X.toObj(X.removeWhite(xml)), xml.nodeName, "\t");
                    return "{\n" + tab + (tab ? json.replace(/\t/g, tab) : json.replace(/\t|\n/g, "")) + "\n}";
                };
            }])
             //  公共接口 
             .factory('commonInterface', [function () {
                 //数组去重
                 var unique =function(arr){
                    var result = [], hash = {};
                    for (var i = 0, elem; (elem = arr[i]) != null; i++) {
                        if (!hash[elem]) {
                            result.push(elem);
                            hash[elem] = true;
                        }
                    }
                    return result;
                 };
                 
                 //获取导购员
                var get_guides_user_name = function(arr_detail){
                    var arr_guides_name = [];
                    arr_detail.forEach(function(n){
                        arr_guides_name.push(n.guide_user_name || n.daogou_name);
                    });
                    var arr_final_names =[];
                    var guides_user_name = '';
                    //去掉重复的名字
                    arr_final_names = unique(arr_guides_name);
                    arr_final_names.forEach(function(n){
                        guides_user_name += n+',';
                    });
                    guides_user_name = guides_user_name.substring(0,guides_user_name.length-1);
                    return guides_user_name;
                };
                 
                 
                 return {
                     get_guides_user_name:get_guides_user_name
                 };
            }])
        /**
         * 返回最近3天、7天、30天的日期字符串
         * @param {number} days 3/7/30
         * @returns {string}
         * @requires common.js
         */
        .factory('changeDate', [function () {
                return function (days, type) {
                    var today = new Date(); // 获取今天时间
                    var begin, end;
                    if (days === 1) {
                        today.setTime(today.getTime());
                        begin = today.format('yyyy-MM-dd');
                        end = new Date().format('yyyy-MM-dd');
                    } else if (days === 3) {
                        today.setTime(today.getTime() - 3 * 24 * 3600 * 1000);
                        begin = today.format('yyyy-MM-dd');
                        end = new Date().format('yyyy-MM-dd');
                    } else if (days === 7) {
                        today.setTime(today.getTime() - 7 * 24 * 3600 * 1000);
                        begin = today.format('yyyy-MM-dd');
                        end = new Date().format('yyyy-MM-dd');
                    } else if (days === 30) {
                        today.setTime(today.getTime() - 30 * 24 * 3600 * 1000);
                        begin = today.format('yyyy-MM-dd');
                        end = new Date().format('yyyy-MM-dd');
                    }
                    if (typeof type != 'undefined' && type == 1) {
                        return begin;
                    }
                    return end;
                };
            }]);
//      /**
//       *点击系统返回键使其退出系统 
//       */
//       .factory('checkExitApp', [function () {
//              return function () {
//                  //按住返回键退出程序
//				    //定义个时间标志变量
//					var mkeyTime = new Date().getTime();
//						var header = $api.byId('header');
//						$api.fixIos7Bar(header);
//						baison_app.api.addEventListener({
//							name : "keyback"
//						}, function(ret, err) {
//							//如果当前时间减去标志时间大于2秒，说明是第一次点击返回键，反之为2秒内点了2次，则退出。
//							if ((new Date().getTime() - mkeyTime) > 2000) {
//								mkeyTime = new Date().getTime();
//								baison_app.api.toast({
//									msg : '再按一次退出程序',
//									duration : 2000,
//									location : 'bottom'
//								});
//							} else {
//								baison_app.api.closeWidget();
//							}
//					
//					});
//              };
//          }]);
//


